#include "configiniutil.h"

#include <QSettings>

QString ConfigIniUtil::readConfigValue(const QString &iniPath, const QString &key)
{
    QSettings configSetting(iniPath, QSettings::IniFormat);
    if (key.split("/").count() != 2)
    {
        return "";
    }
    return configSetting.value(key).toString();
}

bool ConfigIniUtil::writeConfigValue(const QString &iniPath, const QString &key, const QVariant &value)
{
    QSettings configSetting(iniPath, QSettings::IniFormat);
    if (key.split("/").count() != 2)
    {
        return false;
    }
    configSetting.setValue(key, value);
    return true;
}

bool ConfigIniUtil::writeConfigValues(const QString &iniPath, const QString &group, const QVariantMap &values)
{
    if (group.isEmpty()) return false;

    QSettings configSetting(iniPath, QSettings::IniFormat);
    configSetting.beginGroup(group);
    QVariantMap::const_iterator it;
    for (it = values.cbegin(); it != values.cend(); ++it)
    {
        configSetting.setValue(it.key(), it.value());
    }
    configSetting.endGroup();
    return true;
}

bool ConfigIniUtil::deleteConfig(const QString &iniPath, const QString &key)
{
    QSettings configSetting(iniPath, QSettings::IniFormat);
    if (key.split("/").count() != 2)
    {
        return false;
    }
    configSetting.remove(key);
    return true;
}

QVariantMap ConfigIniUtil::readConfigValues(const QString &iniPath)
{
    QVariantMap values;
    QSettings setting(iniPath, QSettings::IniFormat);
    QStringList groupList = setting.childGroups();
    for (const QString &group : groupList)
    {
        QVariantMap vl;
        setting.beginGroup(group);
        foreach (QString key, setting.childKeys())
            vl.insert(key, setting.value(key));
        setting.endGroup();
        values.unite(vl);
    }
    return values;
}
